//
// Created by 孙凌霄 on 2021/6/30.
//

#include "JavaCallHelper.h"
#include "macro.h"

JavaCallHelper::JavaCallHelper(JavaVM *vm, JNIEnv *env, jobject instance) {
    this->vm = vm;
    // env用于在主线程回调
    this->env = env;

    // 设计到jobject跨方法 跨线程使用就需要提升为全局引用，防止出栈被回收
    this->instance = env->NewGlobalRef(instance);

    jclass clz = env->GetObjectClass(instance);
    onErrorId = env->GetMethodID(clz, "onError", "(I)V");
    onPrepareId = env->GetMethodID(clz, "onPrepare", "()V");
}

JavaCallHelper::~JavaCallHelper() {
    env->DeleteGlobalRef(instance);
}

void JavaCallHelper::onError(int thread, int errorCode) {
    // 在主线程,直接使用env
    if (thread == THREAD_MAIN) {
        env->CallVoidMethod(instance, onErrorId, errorCode);
    } else {
        // 子线程，获取当前线程的env对象
        JNIEnv *childEnv;
        vm->AttachCurrentThread(&childEnv, nullptr);
        childEnv->CallVoidMethod(instance, onErrorId, errorCode);
        vm->DetachCurrentThread();
    }
}

void JavaCallHelper::onPrepare(int thread) {
    if (thread == THREAD_MAIN) {
        env->CallVoidMethod(instance, onPrepareId);
    } else {
        JNIEnv *childEnv;
        vm->AttachCurrentThread(&childEnv, nullptr);
        childEnv->CallVoidMethod(instance, onPrepareId);
        vm->DetachCurrentThread();
    }
}